import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';

import { httpInterface } from './interface/http.interface';
import { HTTP_URL, HTTP_SUCCESS } from '../app/utils';
@Injectable()
export class HttpService implements httpInterface {

  constructor(private http: HttpClient) {
  }

  /**
   * @desc 封装get请求
   * @param url apirequest地址
   * @param options 参数
   */
  async get(url: string, options?: any): Promise<any> {
    let params = new HttpParams();
    options && Object.keys(options).forEach((key: string) => {
      params = params.append(key, options[key]);
    });
    return await this.http.get(`${HTTP_URL}${url}`, { params })
      .toPromise()
      .then((resp: { Data, Messages: string[], StatusCode }) => {
        if (resp.StatusCode == HTTP_SUCCESS)
          return Promise.resolve(resp.Data);
        else
          return Promise.reject(resp.Messages);
      })
      .catch(err => {
        return Promise.reject(err);
      });
  }

  /**
   * @desc 封装post请求
   * @param url apirequest地址
   * @param options 参数
   */
  async post(url: string, options: object = {}): Promise<any> {
    return this.http
      .post(`${HTTP_URL}${url}`, options)
      .toPromise()
      .then((resp: { Data, Messages: string[], StatusCode }) => {
        if (resp.StatusCode == HTTP_SUCCESS)
          return Promise.resolve(resp.Data);
        else
          return Promise.reject(resp.Messages);
      })
      .catch(err => {
        return Promise.reject(err);
      });
  }

}